package com.ruoyi.conference.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.conference.domain.*;
import com.ruoyi.conference.mapper.HuaweiConferenceMapper;
import com.ruoyi.conference.service.IHuaweiConferenceService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/huiCalculatedOrder")
public class ConferenceManagerController {

    //可以用 spring boot 的restTemplate 但是感觉 hutool 的 工具类已经封装好的，比较方便

    @Value("${conference.CreateToken.url}")
    private String createTokenUrl;

    @Value("${conference.CreateMeeting.url}")
    private String createMeetingUrl;

    @Value("${conference.getMemberInfo.url}")
    private String getMemberInfoUrl;

    @Value("${conference.CreateConfToken.url}")
    private String getMeetingControllerTokenUrl;

    @Value("${conference.StopMeeting.url}")
    private String stopMeetingUrl;

    @Value("${conference.getMeetingList.url}")
    private String getMeetingList;



    @Autowired
    private IHuaweiConferenceService huaweiConferenceService;

    /**
     * 获取用户个人信息
     * 2020/11/05
     */
    @GetMapping("/getMemberInfo")
    public MeetingMemberInfo getMemberInfo(){
        ConferenceRequestParams conferenceRequestParams = huaweiConferenceService.ObtainConferenceMemberInfo(createTokenUrl);
        String memberInfoResponse = null;
        memberInfoResponse = HttpRequest.get(getMemberInfoUrl).header("X-Access-Token",conferenceRequestParams.getAccessToken())
                .execute().body();
        JSONObject jsonObject = JSON.parseObject(memberInfoResponse);
        MeetingMemberInfo meetingMemberInfo = JSON.parseObject(JSON.toJSONString(jsonObject), MeetingMemberInfo.class);
        meetingMemberInfo.setConferenceRequestParams(conferenceRequestParams);
        return meetingMemberInfo;
    }

    /**
     * 获取会议ID列表
     */
    public Map<String,String> getMeetingList(ConferenceRequestParams conferenceRequestParams){
        String meetingInfo = null;
        Map<String,Object> paramsMap=new HashMap<>();
        paramsMap.put("ts",System.currentTimeMillis());
        paramsMap.put("limit",10);
        meetingInfo = HttpRequest.get(getMeetingList).header("X-Access-Token",conferenceRequestParams.getAccessToken())
                .form(paramsMap).execute().body();

        Document parse = Jsoup.parse(meetingInfo);
        String conferenceID = parse.getElementsByTag("conferenceID").text();
//        String[] conferenceIDs = conferenceID.split(" ");
        String password = parse.getElementsByTag("password").text();
//        String[] passwords = password.split(" ");
        Map<String,String> map = new HashMap<>();
        map.put("conferenceID",conferenceID);
        map.put("password",password);

//        JSONObject jsonObject = JSON.parseObject(meetingInfo);
//        List<Object> listObject = (List<Object>) jsonObject.get("data");
//        MeetingInfo firstMeetingInfo = JSON.parseObject(JSON.toJSONString(listObject.get(0)), MeetingInfo.class);
        return map;
    }

    /**
     * 创建会议
     * 2020/11/05
     */
    @PostMapping("/createMeeting")
    public MeetingInfo createMeeting() {

        String createMeetingRes = null;
        Map<String,Object> paramsMap=new HashMap<String,Object>();

        MeetingMemberInfo memberInfo = getMemberInfo();
        ConferenceRequestParams conferenceRequestParams = memberInfo.getConferenceRequestParams();

        List<Map<String,String>> attendeesMap = new ArrayList<>();
        Map<String,String> memberInfoMap = new HashMap<>();

        memberInfoMap.put("userUUID",memberInfo.getId());
        memberInfoMap.put("name",memberInfo.getName());
        memberInfoMap.put("sms",memberInfo.getPhone());
        memberInfoMap.put("sip",memberInfo.getSipNum());
        memberInfoMap.put("phone",memberInfo.getSipNum());
        memberInfoMap.put("type","normal");

        attendeesMap.add(memberInfoMap);

        Map<String,Boolean> confConfigInfoMap = new HashMap<>();
        confConfigInfoMap.put("isGuestFreePwd",true);
        confConfigInfoMap.put("isSendNotify",false);



        paramsMap.put("mediaTypes","Video");
        paramsMap.put("vmrFlag",1);
        paramsMap.put("length",45);
        paramsMap.put("attendees",attendeesMap);
        paramsMap.put("confConfigInfo",confConfigInfoMap);
        paramsMap.put("subject","江淮汽车招聘面试");


//        paramsMap.put("account",conferenceAccountInfo.getConferenceUsername());
//        paramsMap.put("clientType",0);

        String jsonString = JSON.toJSONString(paramsMap);
//        Map<String,Object> param = new HashMap<>();
//        param.put("userUUID",conferenceRequestParams.getUserId());
        String accessToken = conferenceRequestParams.getAccessToken();

        createMeetingRes = HttpRequest.post(createMeetingUrl)
                .header("X-Access-Token", accessToken)
                .body(jsonString).execute().body();

        Document parse = Jsoup.parse(createMeetingRes);
        MeetingInfo meetingInfo = new MeetingInfo();
        meetingInfo.setConferenceID(parse.getElementsByTag("conferenceID").text());
        String password = parse.getElementsByTag("password").text();
        String[] s = password.split(" ");
        meetingInfo.setChairPassword(s[0]);
        meetingInfo.setGuestPassword(s[1]);

        meetingInfo.setUserUUID(parse.getElementsByTag("userUUID").text());
        meetingInfo.setChairJoinUri(parse.getElementsByTag("chairJoinUri").text());
        meetingInfo.setGuestJoinUri(parse.getElementsByTag("guestJoinUri").text());

//        JSONObject jsonObject = JSON.parseObject(post);
//        List<Object> meetObjectList = (List<Object>)jsonObject.get("data");
//        Object meetObject = meetObjectList.get(0);

//        return JSON.parseObject(JSON.toJSONString(meetObject), MeetingInfo.class);
        return meetingInfo;
    }

    /**
     * 获取会议会控token
     * @return
     */
    public String getControllerToken(String conferenceID,String password,ConferenceRequestParams conferenceRequestParams){
//        MeetingMemberInfo memberInfo = getMemberInfo();
//        List<MeetingMemberInfo.vmrMeeting> vmrList = memberInfo.getVmrList();
//        if(vmrList.size()==0){
//            return null;
//        }
//        String conferenceId = vmrList.get(0).getVmrId();
        Map<String,Object> paramsMap=new HashMap<String,Object>();
        paramsMap.put("conferenceID",conferenceID);

        String ControllerToken = HttpRequest.get(getMeetingControllerTokenUrl)
//                .header("X-Conference-Authorization", conferenceRequestParams.getAccessToken())
                .header("X-Login-Type", "1")
                .header("X-Password",password)
                .form(paramsMap).execute().body();

        JSONObject jsonObject = JSON.parseObject(ControllerToken);
        JSONObject data = jsonObject.getJSONObject("data");

//        map.put("conferenceID",vmrList.get(0).getVmrId());
        return (String) data.get("token");

    }


    /**
     *
     * 停止会议列表里的第一个会议
     * 2020/11/05
     */
    @GetMapping("/stopMeeting")
    public R stopMeeting(){
        ConferenceRequestParams conferenceRequestParams = huaweiConferenceService.ObtainConferenceMemberInfo(createTokenUrl);
        Map<String, String> meetingList = getMeetingList(conferenceRequestParams);
        String conferenceID = meetingList.get("conferenceID");
        String stopMeetingRes= null;

        String[] conferenceIDs = conferenceID.split(" ");

        if(conferenceIDs[0].equals("")){
            return R.ok();
        }
        String password = meetingList.get("password");
        String[] passwords = password.split(" ");
        for(String id:conferenceIDs){
            String controllerToken = getControllerToken(id,passwords[0],conferenceRequestParams);
            Map<String,Object> paramsMap=new HashMap<String,Object>();
            paramsMap.put("conferenceID",id);

            stopMeetingRes = HttpRequest.put(stopMeetingUrl+"?conferenceID="+id).header("X-Conference-Authorization", controllerToken)
                    .execute().body();

            System.out.println(stopMeetingRes);
        }

        return R.ok();
    }

}

